package com.huhao.smark;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import static com.huhao.smark.Config.*;

public class AddRecordActivity extends AppCompatActivity {

    private RadioGroup rgType;
    private EditText etAmount;
    private Spinner spCategory;
    private Button btnDate;
    private EditText etDescription;
    private Button btnSubmit;
    private long selectedDate;

    private final String[] expenseCategories = {"餐饮", "交通", "购物", "娱乐", "医疗", "教育", "住房", "其他"};
    private final String[] incomeCategories = {"工资", "奖金", "投资", "兼职", "报销", "其他"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_record);

        // 初始化UI组件
        rgType = findViewById(R.id.rg_type);
        etAmount = findViewById(R.id.et_amount);
        spCategory = findViewById(R.id.sp_category);
        btnDate = findViewById(R.id.btn_date);
        etDescription = findViewById(R.id.et_description);
        btnSubmit = findViewById(R.id.btn_submit);

        // 设置默认分类
        updateCategorySpinner(true);

        // 类型切换监听
        rgType.setOnCheckedChangeListener((group, checkedId) -> {
            boolean isExpense = checkedId == R.id.rb_expense;
            updateCategorySpinner(isExpense);
        });

        // 使用DatePickerDialog
        final Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                (view, selectedYear, selectedMonth, selectedDay) -> {
                    calendar.set(selectedYear, selectedMonth, selectedDay);
                    selectedDate = calendar.getTimeInMillis();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                    btnDate.setText(sdf.format(new Date(selectedDate)));
                },
                year,
                month,
                day
        );

        btnDate.setOnClickListener(v -> datePickerDialog.show());

        // 提交按钮点击事件
        btnSubmit.setOnClickListener(v -> {
            if (validateForm()) {
                addNewRecord();
            }
        });
    }

    // 更新分类下拉列表
    private void updateCategorySpinner(boolean isExpense) {
        String[] categories = isExpense ? expenseCategories : incomeCategories;
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_item,
                categories
        );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spCategory.setAdapter(adapter);
    }

    // 表单验证
    private boolean validateForm() {
        String amount = etAmount.getText().toString().trim();

        if (amount.isEmpty()) {
            etAmount.setError("请输入金额");
            return false;
        }

        try {
            double amt = Double.parseDouble(amount);
            if (amt <= 0) {
                etAmount.setError("金额必须大于0");
                return false;
            }
        } catch (NumberFormatException e) {
            etAmount.setError("请输入有效金额");
            return false;
        }

        return true;
    }

    // 添加新记录
    private void addNewRecord() {
        // 获取用户输入
        boolean isExpense = rgType.getCheckedRadioButtonId() == R.id.rb_expense;
        int type = isExpense ? 1 : 0;
        String category = (String) spCategory.getSelectedItem();
        double amount = Double.parseDouble(etAmount.getText().toString().trim());
        String description = etDescription.getText().toString().trim();
        String url = HTTP + IP + PORT + ADD_RECORD;
        // 格式化日期 (ISO 8601)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        String recordDate = sdf.format(new Date(selectedDate));

        // 构建JSON
        JSONObject json = new JSONObject();
        try {
            json.put("type", type);
            json.put("category", category);
            json.put("price", amount);
            json.put("remark", description);
            json.put("bookDate", recordDate);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // 获取token
        SharedPreferences prefs = getSharedPreferences("app_prefs", Context.MODE_PRIVATE);
        String token = prefs.getString("token", "");
        if (token.isEmpty()) {
            Toast.makeText(this, "用户未登录", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 创建请求
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(
                json.toString(),
                MediaType.parse("application/json; charset=utf-8")
        );

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Authorization", "Bearer " + token)
                .build();

        // 显示加载状态
        btnSubmit.setEnabled(false);
        btnSubmit.setText("提交中...");

        // 发送请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    btnSubmit.setEnabled(true);
                    btnSubmit.setText("添加记录");
                    Toast.makeText(AddRecordActivity.this, "网络错误: " + e.getMessage(), Toast.LENGTH_LONG).show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                runOnUiThread(() -> {
                    btnSubmit.setEnabled(true);
                    btnSubmit.setText("添加记录");

                    if (response.isSuccessful()) {
                        try {
                            JSONObject resJson = new JSONObject(response.body().string());
                            if (resJson.getBoolean("success")) {
                                Toast.makeText(AddRecordActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                                setResult(RESULT_OK);
                                finish();
                            } else {
                                Toast.makeText(AddRecordActivity.this,
                                        "添加失败: " + resJson.getString("message"),
                                        Toast.LENGTH_LONG).show();
                            }
                        } catch (Exception e) {
                            Toast.makeText(AddRecordActivity.this,
                                    "解析响应失败", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(AddRecordActivity.this,
                                "请求失败: " + response.code(), Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
    }
}